const fs = require('fs');
const path = require('path');

function requireAll(config) {
    const dirs = path.join(config.dirname).replace(path.resolve(), '').split(path.sep).filter(d => d);
    let paths = [path.resolve()];
    dirs.forEach(dir => {
        if (dir === '**') {
            const paths2 = [];
            paths.forEach(p => {
                const subDirs = fs.readdirSync(p);
                paths2.push(...subDirs.map(d => path.join(p, d)).filter(d => fs.existsSync(d)));
            });
            paths = paths2;
        } else {
            paths = paths.map(p => path.join(p, dir)).filter(p => fs.existsSync(p));
        }
    });
    const files = [];
    paths.forEach(p => {
        files.push(...fs.readdirSync(p).filter(config.fileFilter).map(f => path.join(p, f)));
    });
    return files.map(f => require(f));
}

module.exports = { requireAll };
